<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件快传</title>
    <link rel="stylesheet" href="/filetrans/css/style.css">
    <!-- 引入Font Awesome图标库 -->
    <!--    <link rel="stylesheet" href="/css/all.min.css">-->
    <style>

        /* Font Awesome图标 */
        .fa-users-cog {
            margin-right: 5px;
        }

        /******************/
        /* 添加一些基本样式确保用户菜单可见 */
        .user-avatar {
            cursor: pointer;
            font-size: 2rem;
            color: #333;
        }

        /* 更新用户按钮样式 */
        .user-btn {
            background: none;
            border: none;
            color: #333;
            cursor: pointer;
            padding: 8px 12px;
            width: 100%;
            text-align: left;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
            border-radius: 4px;
            margin: 2px 0;
            transition: all 0.2s;
        }

        .user-btn:hover {
            background-color: #f0f0f0;
            color: #0066cc;
        }

        .user-btn i {
            width: 18px;
            text-align: center;
        }

        /* 调整下拉菜单内边距 */
        .dropdown-content {
            padding: 8px 0;
        }


        /* 修改header样式为flex布局，让内容靠右 */
        header {
            display: flex;
            justify-content: flex-end; /* 改为flex-end让内容靠右 */
            align-items: center;
            padding: 1rem;
            background-color: #f5f5f5;
        }

        /* 添加upload-section的定位样式 */
        .upload-section {
            position: relative;
        }

        /* 调整用户菜单的位置 */
        .user-menu {
            position: absolute; /* 改为绝对定位 */
            top: 1rem;
            right: 1rem;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 在顶部用户信息区域添加管理员按钮 -->
    <div class="upload-section">
        <!-- 将用户菜单移到这里 -->
        <div class="user-menu">
            <div class="user-avatar" id="userAvatar">
                <svg width="32" height="32" viewBox="0 0 512 512" fill="#333">
                    <path d="M256 256c70.7 0 128-57.3 128-128S326.7 0 256 0 128 57.3 128 128s57.3 128 128 128zm0 32c-84.4 0-256 42.7-256 128v64h512v-64c0-85.3-171.6-128-256-128z"/>
                </svg>
            </div>

            <div class="dropdown-content" id="userDropdown">
                <div class="user-info">
                    <span id="usernameDisplay"></span>
                </div>
                <form th:action="@{/filetrans/logout}" method="post" class="logout-form">
                    <button id="admin-btn" type="button" class="user-btn"
                            onclick="window.open('/filetrans/admin/users', '_blank')">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"
                             stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M17 21v-2a4 4 0 0 0-3-3.87"></path>
                            <path d="M7 21v-2a4 4 0 0 1 3-3.87"></path>
                            <circle cx="12" cy="7" r="4"></circle>
                        </svg>
                        用户管理
                    </button>
                    <button type="submit" class="user-btn">
                        <svg width="16" viewBox="0 0 512 512" fill="currentColor">
                            <path d="M160 80h192v80h32V48H128v416h256v-112h-32v80H160z"/>
                            <path d="M352 256l-96-96v64H96v64h160v64z"/>
                        </svg>
                        退出登录
                    </button>

                </form>
            </div>
        </div>

        <h3>上传文件</h3>
        <div id="upload-container">
            <input type="file" id="file-input">
            <button id="upload-btn">上传</button>
            <div id="upload-progress" style="display: none; margin-top: 10px;">
                <div class="progress-container">
                    <div class="progress-bar" style="width: 0%"></div>
                </div>
                <div class="progress-text">0%</div>
                <div class="upload-status"></div>
            </div>
        </div>
    </div>

    <div class="file-list">
        <h2>文件列表</h2>
        <div id="file-list-container">
            <!-- 动态加载文件列表 -->
            <table>
                <thead>
                <tr>
                    <th>文件名</th>
                    <th>大小</th>
                    <th>类型</th>
                    <th>创建人</th>
                    <th>上传时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="file-list-body">
                <!-- 文件列表将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="/filetrans/js/script.js"></script>
<script>
    // 页面加载时获取文件列表和检查用户状态
    document.addEventListener('DOMContentLoaded', function () {

        // 或者通过API检查权限（更安全）
        checkAdminPermission();

        loadFileList();
        checkAuthStatus();

        // 用户头像点击事件
        document.getElementById('userAvatar').addEventListener('click', function () {
            document.getElementById('userDropdown').classList.toggle('show');
        });

        // 点击页面其他地方关闭下拉菜单
        window.addEventListener('click', function (event) {
            if (!event.target.matches('.user-avatar') && !event.target.closest('.user-avatar')) {
                const dropdowns = document.getElementsByClassName("dropdown-content");
                for (let i = 0; i < dropdowns.length; i++) {
                    const openDropdown = dropdowns[i];
                    if (openDropdown.classList.contains('show')) {
                        openDropdown.classList.remove('show');
                    }
                }
            }
        });
    });

    // 通过API检查管理员权限
    function checkAdminPermission() {
        fetch('/filetrans/auth/check-admin')
            .then(response => response.text())
            .then(data => {
                if (data === '1') {
                    showAdminButton();
                }
            });
    }

    // 显示管理员按钮
    function showAdminButton() {
        const adminPanel = document.getElementById('admin-btn');
        adminPanel.style.display = 'inline-block';
    }

    // 检查认证状态并更新UI
    function checkAuthStatus() {
        fetch('/filetrans/auth/status')
            .then(response => {
                if (!response.ok) {
                    throw new Error('未认证');
                }
                return response.json();
            })
            .then(data => {
                if (data.authenticated) {
                    document.getElementById('usernameDisplay').textContent = "   你好： " + data.username;
                    document.getElementById('userAvatar').style.display = 'flex';
                } else {
                    window.location.href = '/filetrans/login';
                }
            })
            .catch(error => {
                console.error('检查认证状态失败:', error);
                window.location.href = '/filetrans/login';
            });
    }

    // 检查认证状态并更新UI
    async function checkAndDownload(fileId, filename) {
        try {
            // 检查用户名是否存在
            const response = await fetch(`/filetrans/files/prepare/${fileId}`);
            const data = await response.text(); // 后端返回纯文本

            if (data === '0') {
                alert("没有查询到这条记录!")
                return false;
            } else if (data === '1') {
                alert("文件已移动或删除!")
            } else {
                const a = document.createElement('a');
                a.href = `/filetrans/files/download/${data}`;
                a.download = decodeURIComponent(filename); // 处理中文名
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
        } catch (error) {
            console.error('检查认证状态失败:', error);
        }
    }

    // 加载文件列表
    function loadFileList() {
        fetch('/filetrans/files')
            .then(response => response.json())
            .then(files => {
                const tbody = document.getElementById('file-list-body');
                tbody.innerHTML = '';

                files.forEach(file => {
                    const row = document.createElement('tr');

                    row.innerHTML = `
                        <td>${file.filename}</td>
                        <td>${formatFileSize(file.size)}</td>
                        <td>${file.fileType || '未知'}</td>
                        <td>${file.creator || '未知'}</td>
                        <td>${formatDateTime(file.uploadTime)}</td>
                        <td style="display:flex">
                            <a onclick="checkAndDownload(${file.id})" class="btn download">下载</a>
                            <a href="#" onclick="deleteFile(${file.id})" class="btn delete">删除</a>
                        </td>
                    `;

                    tbody.appendChild(row);
                });
            })
            .catch(error => console.error('加载文件列表失败:', error));
    }

    // 删除文件
    function deleteFile(fileId) {
        if (confirm('确定要删除这个文件吗？')) {
            fetch(`/filetrans/files/${fileId}`, {
                method: 'DELETE'
            })
                .then(response => {
                    if (response.ok) {
                        loadFileList(); // 刷新列表
                    }
                });
        }
    }

    // 辅助函数：格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 辅助函数：格式化日期时间
    function formatDateTime(dateTimeStr) {
        const date = new Date(dateTimeStr);
        return date.toLocaleString();
    }
</script>
</body>
</html>